Generics allow us to design classes and methods decoupled from data types. Generic classes available in System. Collections. Generic namespace. Generics make your code, type independent and that way you can reuse your code with any type. If you use generics you will get the strongest type nature and also get a performance gain from unnecessary boxing and unboxing.
Example:
If you want to compare two string or integer are equal.
To make CompareEqual() method generic , specify a type parameter using angular brackets as shown below
public static bool CompareEqual<T>(T Val1, T Val2)
Demo:
using System;
using System.Collections.Generic;
namespace Demoproject
{
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
bool result = sample.CompareEqual<string>("infinetsoft", "infinetsoft");
if (result)
{
HttpContext.Current.Response.Write("Equal");
}
else
{
HttpContext.Current.Response.Write("NotEqual");
}
}
}
public class sample
{
public static bool CompareEqual<T>(T Val1, T Val2)
{
return Val1.Equals(Val2);
}
}
}
Generic class:
If you want to use generic class, specify a type parameter using angular brackets as shown below
public class sample<T>
and invoke a method like
bool result = sample<string>.CompareEqual("infinetsoft", "infinetsoft");
Description:
Here I am using string data type for comparison, likewise you can use any data type. T mentioned as a type parameter.
Post your comments / questions
Recent Article
- How to create custom 404 error page in Django?
- Requested setting INSTALLED_APPS, but settings are not configured. You must either define..
- ValueError:All arrays must be of the same length - Python
- Check hostname requires server hostname - SOLVED
- How to restrict access to the page Access only for logged user in Django
- Migration admin.0001_initial is applied before its dependency admin.0001_initial on database default
- Add or change a related_name argument to the definition for 'auth.User.groups' or 'DriverUser.groups'. -Django ERROR
- Addition of two numbers in django python
Related Article